<template>
  <view>
    <view class="bg-white">
      <uni-forms class="search-block" ref="form" :modelValue="searchForm" labelWidth="70vw" labelPosition="top">
        <view class="background-white">
          <uni-forms-item name="itemId">
            <cu-cell-select
              v-model="searchForm.itemId"
              :required="false"
              :list="itemList"
              labelKey="itemName"
              valueKey="itemId"
              title="排班事项"
              placeholder="请选择排班事项"
              @confirm="itemChange"
            ></cu-cell-select>
          </uni-forms-item>
          <uni-forms-item name="teamMonth" label="选择月份" class="month-label">
            <picker
              class="month-input"
              mode="date"
              :value="searchForm.teamMonth"
              fields="month"
              :disabled="!searchForm.itemId"
              @change="monthPick"
            >
              <input v-model="searchForm.teamMonth" placeholder="请选择月份" disabled />
            </picker>
          </uni-forms-item>
        </view>
      </uni-forms>
    </view>
    <!-- 日历主体 -->
    <view class="duty-calendar-container" v-if="searchForm.teamMonth">
      <view class="calendar-main">
        <view class="flex align-center calendar-header">
          <uni-icons @click="backHandler" type="back" class="back-icon"></uni-icons>
          <view class="flex align-center">
            <view>{{ year }}年{{ month < 10 ? '0' + month : month }}月</view>
            <image class="calendar-icon" src="/static/images/work/calendar.png" mode="aspectFit" />
          </view>
          <uni-icons @click="forwardHandler" type="forward" class="forward-icon"></uni-icons>
        </view>
        <view class="calendar-content">
          <view class="week-number">
            <view v-for="(item, index) in weekList" :key="index">
              {{ item }}
            </view>
          </view>
          <view class="each-day-wrap">
            <view class="each-day-item" v-for="(d, idx) in dayList" :key="idx">
              <view :class="d.day === day ? 'current' : 'normal'" v-if="day">
                <view class="date">
                  {{ d.day ? d.day : '' }}
                </view>
                <view v-if="d" class="shift">
                  <view class="shift-dot" :style="{ background: getDateColor(d.classNames) }"></view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="shift-wrap" v-if="banCiList.length > 0">
        <view class="title">对应班次</view>
        <view class="shift-rule-wrap">
          <view class="shift-rule-item" v-for="(item, index) in banCiList" :key="index">
            <view class="dot" :style="{ background: item.color }"></view>
            {{ `${item.className}：当值时间${item.startTime || '--'}~${item.endTime || '--'}` }}
          </view>
        </view>
      </view>

      <!--<view class="shift-wrap">
				<view class="title">对应班次</view>
				<view class="shift-rule-wrap">
					<view class="shift-rule-item" v-for="(item,index) in shiftRules" :key="index">
						<view class="dot" :style="{background: item.color}"></view>
						{{`${item.shiftRuleDetailDescription}：当值时间${item.shiftStartTime || '&#45;&#45;'}~${item.shiftEndTime || '&#45;&#45;'}`}}
					</view>
				</view>
			</view>-->
    </view>
  </view>
</template>

<script>
import CuCellSelect from '@/components/cu-cell/cu-cell-select.vue'
import { getShiftItem } from '@/api/duty-basic/duty-meeting'
import { getBanCi, getShiftCalendar } from '@/api/duty-basic/duty-shifting.js'
import { mapGetters } from 'vuex'

export default {
  components: {
    CuCellSelect
  },
  data() {
    return {
      itemList: [],
      banCiList: [],
      searchForm: {
        itemId: '',
        teamMonth: ''
      },
      weekList: ['日', '一', '二', '三', '四', '五', '六'],
      //  月份数组【2020-08-01   2020-09-01   2020-10-01】
      year: 2020,
      month: 10,
      day: 10,
      dayList: [],
      start_time: '', //  月初的时间戳
      end_time: '', //  月末的时间戳
      calendarData: [],
      colorArr: ['#88B4C4', '#C4C088', '#CBCED6', '#C87C32', '#30A199', '#7E84A3', '#B46790'],
      // colorArr: ['blue', 'red', 'black', 'green', 'yellow','pink','#B46790'],
      shiftRules: [],
      selectedDept: undefined
    }
  },
  computed: {
    ...mapGetters(['deptId', 'deptName'])
  },
  created() {
    this.selectedDept = {
      name: this.deptName,
      value: this.deptId
    }
    // this.initTime()

    this.getItem(1)
  },
  methods: {
    navigateBack() {
      uni.navigateBack()
    },
    getItem(type) {
      getShiftItem({
        type: type
      }).then((res) => {
        this.itemList = res.data
      })
      this.initTime()
    },
    itemChange(val) {
      this.queryBanCi(val.itemId)
      if (!this.searchForm.teamMonth) {
        return
      } else {
        this.queryCalendar()
      }
    },
    async queryBanCi() {
      const res = await getBanCi(this.searchForm.itemId)
      res.data.map((item, index) => (item.color = this.colorArr[index]))
      this.banCiList = res.data
    },
    monthPick(e) {
      console.log('monthPick事件:', e)
      let date = e.detail.value
      this.searchForm.teamMonth = date
      let m = date.split('-')[1]
      this.month = Number(m)
      this.queryCalendar()
    },
    /*getDateColor(date) {
				const arr = this.shiftRules
				const dateData = this.getTodaySchedule(date)
				if (dateData && dateData.length > 0) {
					for (var i = 0; i < arr.length; i++) {
						if (arr[i].shiftRuleDetailDescription == dateData[0].shiftRuleDetailDescription) {
							return arr[i].color
						}
					}
				}
			},*/

    getDateColor(classNames) {
      let bc = this.banCiList.find((ban) => {
        return ban.className === classNames
      })
      return bc?.color || ''
    },

    getTodaySchedule(date) {
      console.log('date', date)
      console.log('calendarData', this.calendarData)
      if (this.calendarData.length > 0) {
        for (let i = 0; i < this.calendarData.length; i++) {
          const ele = this.calendarData[i]
          if (ele && ele.onDutyDate) {
            if (new Date(ele.onDutyDate).getDate() === date) {
              return ele.onDutyDetails
            }
          }
        }
      } else {
        return false
      }
    },
    async queryCalendar() {
      const res = await getShiftCalendar({
        itemId: this.searchForm.itemId,
        teamMonth: this.searchForm.teamMonth,
        type: 1
      })
      // this.calendarData = res.data
      this.dayList = res.data.onDutyDetails

      const count = this.getDayNum(this.month, this.year)
      // console.log('count', count)
      const _week = new Date(this.year + '/' + this.month + '/1').getDay()
      for (let i = 0; i < _week; i++) {
        this.dayList.unshift({
          day: null,
          classNames: ''
        })
      }
      // console.log('dayList', this.dayList)
    },

    //  初始化时间
    initTime() {
      const nowTimeData = this.getTimeNow()
      console.log('nowTimeData', nowTimeData)

      this.year = nowTimeData.year
      this.month = nowTimeData.month
      this.day = nowTimeData.day

      // 今日时间为：2022-12-19
      console.log('今日时间为：' + this.year + '-' + this.month + '-' + this.day)
      // this.initApi()
    },

    getTimeNow() {
      //  初始化时间
      const date = new Date()

      const year = date.getFullYear()
      let month = parseInt(date.getMonth() + 1)
      let day = date.getDate()

      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      let returnData = {
        year: year,
        month: parseInt(month),
        day: day
      }
      return returnData
    },
    backHandler() {
      if (this.month === 1) {
        this.year = this.year - 1
        this.month = 12
      } else {
        this.month = this.month - 1
      }
      // this.initApi()
      let m = this.month < 10 ? '0' + this.month : this.month
      this.searchForm.teamMonth = `${this.year}-${m}`
      this.queryCalendar()
    },
    forwardHandler() {
      if (this.month === 12) {
        this.year = this.year + 1
        this.month = 1
      } else {
        this.month = this.month + 1
      }
      // this.initApi()
      let m = this.month < 10 ? '0' + this.month : this.month
      this.searchForm.teamMonth = `${this.year}-${m}`
      this.queryCalendar()
    },

    //  获取当前月的每一天的数据
    initApi() {
      this.dayList = this.createDayList(this.month, this.year)
    },

    //创建每个月日历数据，传入月份1号前面用null填充
    createDayList(month, year) {
      const count = this.getDayNum(month, year),
        _week = new Date(year + '/' + month + '/1').getDay()
      let list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]

      for (let i = 29; i <= count; i++) {
        list.push(i)
      }
      for (let i = 0; i < _week; i++) {
        list.unshift(null)
      }
      return list
    },
    //计算传入月份有多少天
    getDayNum(month, year) {
      let dayNum = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

      if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
        dayNum[1] = 29
      }
      return dayNum[month - 1]
    }
  }
}
</script>

<style lang="scss" scoped>
.search-block {
  width: 90%;
  margin: 0 auto;
}
.bg-white {
  padding-bottom: 10rpx;
  ::v-deep .no-label {
    display: none;
  }
}
.month-label {
  display: inline-flex;
  flex-direction: row !important;
  align-items: baseline;
  width: 95%;
  ::v-deep .uni-forms-item__label {
    width: 20vw !important;
    font-size: 16px;
  }
  ::v-deep .uni-forms-item__content {
    display: flex;
    justify-content: flex-end;
    height: 30px;
  }
}
.month-input {
  border: 1px solid #ccc;
  border-radius: 3px;
  ::v-deep .uni-input-wrapper {
    height: 30px;
    .uni-input-placeholder {
      font-size: 15px;
      color: #bbbbbb;
    }
  }
  ::v-deep input {
    text-indent: 10px;
    font-size: 15px;
    line-height: 30px;
  }
}
.duty-calendar-container {
  .select-dept-wrap {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 100rpx;
    border-radius: 20rpx;
    background: #fff;
    margin: 30rpx;
    padding: 20rpx;

    .left-text {
      font-size: 30rpx;
      color: #333333;
    }

    .right-label {
      font-size: 28rpx;
      .dept-name {
        color: #333;
      }
      .placeholder {
        color: #bbbbbb;
      }
    }
  }

  .calendar-main {
    margin: 30rpx;
    background: #fff;
    border-radius: 20rpx;
    padding: 30rpx 0;

    .calendar-header {
      font-size: 32rpx;
      color: #333333;
      justify-content: center;
      line-height: 44rpx;
      padding-bottom: 50rpx;

      .back-icon,
      .forward-icon {
        font-size: 12rpx;
        color: #999;
        padding: 12rpx;
      }

      .back-icon {
        margin-right: 60rpx;
      }

      .forward-icon {
        margin-left: 60rpx;
      }

      .calendar-icon {
        width: 34rpx;
        height: 34rpx;
        margin-left: 8rpx;
      }
    }

    .calendar-content {
      .week-number {
        display: flex;
        font-size: 32rpx;
        color: #333333;
        justify-content: space-around;
        padding-bottom: 30rpx;
      }

      .each-day-wrap {
        position: relative;
        display: flex;
        flex-wrap: wrap;

        .each-day-item {
          width: 14.28%;
          min-height: 78rpx;
          margin-bottom: 30rpx;

          .normal,
          .current {
            display: flex;
            flex-direction: column;
            align-items: center;

            .date {
              font-size: 34rpx;
              color: #333;
              width: 50rpx;
              line-height: 50rpx;
              text-align: center;
              border-radius: 50rpx;
            }

            .shift {
              font-size: 22rpx;
              color: #666666;
              line-height: 30rpx;
              .shift-dot {
                display: inline-block;
                width: 12rpx;
                height: 12rpx;
                border-radius: 12rpx;
              }
            }
          }

          .current {
            .date {
              color: #fff;
              background: #88b4c4;
            }
          }
        }
      }
    }
  }

  .shift-wrap {
    margin: 30rpx;
    padding: 20rpx 30rpx;
    border-radius: 20rpx;
    background: #fff;

    .title {
      font-size: 30rpx;
      color: #333333;
      line-height: 42rpx;
      margin-bottom: 16rpx;
    }

    .shift-rule-wrap {
      font-size: 26rpx;
      color: #666666;

      .shift-rule-item {
        line-height: 38rpx;
        margin-bottom: 16rpx;

        .dot {
          display: inline-block;
          width: 12rpx;
          height: 12rpx;
          border-radius: 12rpx;
          vertical-align: 4rpx;
          margin-right: 7rpx;
        }
      }
    }
  }
}
</style>
